package controllers

import (
	"2301_shop/models"
	beego "github.com/beego/beego/v2/server/web"
	"math"
)

type MainController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type MsgJsonR struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Count   int64       `json:"count"`
	Sumpage int         `json:"sumpage"`
	Size    int         `json:"size"`
}

func (c *MainController) Add() {
	name := c.GetString("name")
	price, _ := c.GetInt("price")
	wegiht, _ := c.GetInt("weight")
	number, _ := c.GetInt("number")
	time := c.GetString("time")
	var shop = models.Shop{
		Name:   name,
		Price:  price,
		Weight: wegiht,
		Number: number,
		Time:   time,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: shop,
		}
		c.ServeJSON()
	}
}
func (c *MainController) Page() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Shop{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size
	var allshop []models.Shop
	err := models.DB.Offset(offset).Limit(size).Find(&allshop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "分页查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = MsgJsonR{
			Code:    200,
			Msg:     "分页查询成功",
			Data:    allshop,
			Page:    page,
			Count:   count,
			Sumpage: sumpage,
			Size:    size,
		}
		c.ServeJSON()
	}
}
func (c *MainController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Shop{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
